package classconverstation.cscl.ist.psu.edu.server;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.openid4java.OpenIDException;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.AuthSuccess;
import org.openid4java.message.ParameterList;
import org.openid4java.message.ax.AxMessage;
import org.openid4java.message.ax.FetchRequest;
import org.openid4java.message.ax.FetchResponse;


/**
 * Servlet Filter implementation class OpenIDFilter
 */
public class OpenIDFilter implements Filter {
    final static String YAHOO_ENDPOINT = "https://me.yahoo.com";
    final static String GOOGLE_ENDPOINT = "https://www.google.com/accounts/o8/id";
    public static final String CURRENT_USER = "CURRENT_USER";
    
//    private OpenIDAuthenticator openID_authenticator;
    /**
     * Default constructor. 
     */
    public OpenIDFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
//        this.openID_authenticator = new OpenIDAuthenticator();
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	    HttpServletRequest httpReq = (HttpServletRequest)request;
        HttpServletResponse httpResp= (HttpServletResponse)response;

//        System.out.println("--------->" + httpResp.toString());
	    HttpSession session = httpReq.getSession();
	    String user_ = (String) session.getAttribute(OpenIDFilter.CURRENT_USER);
//	    System.out.println("--------->" + user_);
	    if (user_ == null) { 
	        authenticate((HttpServletRequest)request, (HttpServletResponse)response);
	    }
	    else {
    	    chain.doFilter(request, response);
	    }
	}
	
	private void authenticate(HttpServletRequest httpReq, HttpServletResponse httpResp) throws IOException {
//	    String requestedPage = getRequestedPage(httpReq);
//	    System.out.println(URLEncoder.encode("http://cscl.ist.psu.edu:5678/OpenIDTry/secured/index.html?ip=url", "ISO-8859-1"));
//	    httpResp.sendRedirect("../lg.jsp?url=" + URLEncoder.encode("http://cscl.ist.psu.edu:5678/OpenIDTry/secured/index.html?ip=url", "ISO-8859-1"));
        httpResp.sendRedirect("../lg.jsp?url=" + getRequestedPage(httpReq));
	    
//	    OpenIDAuthenticator.createOpenIdAuthRequest(discoveryInformation, "/service/OpenIDCheck");
	}
	
	private String getRequestedPage( 
            HttpServletRequest aHttpRequest) { 
//        String url = aHttpRequest.getRequestURI(); 
//        int firstSlash = url.indexOf("/",1); 
//        String requestedPage = null; 
//        if (firstSlash != -1) requestedPage = 
//            url.substring(firstSlash + 1, url.length()); 
//        return requestedPage; 
	    String fullURL = aHttpRequest.getRequestURL().append("?").append( 
	            aHttpRequest.getQueryString()).toString();
	    return fullURL;
    } 
}
